package com.ruoyi.conference.service.Impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.conference.domain.ConferenceAccountInfo;
import com.ruoyi.conference.domain.ConferenceRequestParams;
import com.ruoyi.conference.mapper.HuaweiConferenceMapper;
import com.ruoyi.conference.service.IHuaweiConferenceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Service
public class HuaweiConferenceServiceImpl implements IHuaweiConferenceService {

    @Autowired
    HuaweiConferenceMapper huaweiConferenceMapper;

    @Override
    public ConferenceRequestParams ObtainConferenceMemberInfo(String createTokenUrl) {
        HttpServletRequest request = ServletUtils.getRequest();
        String userid = request.getHeader(Constants.CURRENT_ID);
        ConferenceAccountInfo conferenceAccountInfo = huaweiConferenceMapper.selectConferenceAccountInfo(1l);
        String key = conferenceAccountInfo.getConferenceUsername() + ":" +conferenceAccountInfo.getConferencePassword();
        String newKey = "Basic "+ Base64.encode(key);
        String post = null;
        Map<String,Object> paramsMap=new HashMap<String,Object>();
        paramsMap.put("account",conferenceAccountInfo.getConferenceUsername());
        paramsMap.put("clientType",0);

        String jsonString = JSON.toJSONString(paramsMap);

        post = HttpRequest.post(createTokenUrl)
                .header("Authorization", newKey)
                .header("Content-Type","application/json; charset=UTF-8")
                .body(jsonString).execute().body();

        JSONObject jsonObject = JSON.parseObject(post);

        ConferenceRequestParams user = JSON.parseObject(JSON.toJSONString(jsonObject.get("user")), ConferenceRequestParams.class);
        user.setAccessToken((String) jsonObject.get("accessToken"));

        return user;
    }
}
